import { resolve } from 'path';
import { defineConfig, loadEnv } from 'vite';

import { buildConfig } from './src/utils/build';
import { getExternal } from './build/external';

// 加载引入插件处理方法
import { createVitePlugins } from './build/plugins';

const pathResolve = (dir) => {
	return resolve(__dirname, '.', dir);
};

const viteConfig = defineConfig(({ mode, command }) => {
	const env = loadEnv(mode, process.cwd());
	// 是否生产环境
	const isBuild = command === 'build';
	const external = getExternal({ mode, command, ...env }, isBuild)
	return {
		plugins: [
			JSON.parse(env.VITE_OPEN_CDN) ? buildConfig.cdn() : null,
			...createVitePlugins(env, isBuild)
		],
		base: !isBuild ? './' : env.VITE_PUBLIC_PATH,
		root: process.cwd(),
		resolve: {
			alias: {
				// 项目源码目录别名
				'/@': pathResolve('./src/'),
				// 项目源码目录别名
				'@': pathResolve('src'),
				// 表单列表操作目录别名
				'@hd': pathResolve('src/handler'),
				// 主页设计目录别名
				'@hp': pathResolve('src/components/homepage'),
				// 表单设计目录别名
				'@fp': pathResolve('src/components/formpage'),
				// 视图基础组件目录别名
				'@base': pathResolve('src/views/base'),
			}
		},
		optimizeDeps: {
			exclude: ['vue-demi'],
			include: ['@/../lib/vform/designer.umd.js'],
		},
		server: {
			host: '0.0.0.0',
			port: env.VITE_PORT,
			open: JSON.parse(env.VITE_OPEN),
			hmr: true,
			proxy: {
				'/foxapi': {
					ws: true,
					target: 'https://apifoxmock.com/m1/5678140-5358989-default',
					changeOrigin: true,
					rewrite: (path) => path.replace(new RegExp(`^/foxapi`), ''),
				},
				'/bpmnapi': {
					ws: true,
					target: 'http://192.168.0.123:7088',
					changeOrigin: true,
					rewrite: (path) => path.replace(new RegExp(`^/bpmnapi`), ''),
				},
				'/sys-report': {
					target: env.VITE_API_PROXY,
					ws: true,
					changeOrigin: true,
					// 重写的请求路径
					rewrite: (path) => path.replace(new RegExp(`^/sys-report`), ''),
				},
				[env.VITE_API_URL]: {
					target: env.VITE_API_PROXY,
					changeOrigin: true,
					// 代理websockets
					ws: true,
					// 重写的请求路径
					rewrite: (path) => path.replace(new RegExp(`^${env.VITE_API_URL}`), ''),
				},
			},
		},
		build: {
			outDir: 'dist',
			chunkSizeWarningLimit: 1500,
			commonjsOptions: {
				include: [/node_modules|lib/],
			},
			rollupOptions: {
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^\/]*)\//).groups.moduleName ?? 'vender';
						} else if (id.includes('/src/components/homepage/')) {
							return 'homepage'
						} else if (id.includes('/src/components/formpage/')) {
							return 'formpage'
						} else if (id.includes('/src/handler/')) {
							return 'handler'
						} else if (id.includes('/src/theme/')) {
							return 'theme'
						} else if (id.includes('/src/layout/')) {
							return 'layout'
						} else {
							const matched = id.match(/src\/components\/([^\/]*?)\/src\/([^\/]*?)\//);
							if (matched) { return matched[1] }
						}
					},
				},
				// external: [
				// 	new RegExp('/src/views/custom/ad34/*/.*'),
				// 	new RegExp('/src/handler/modules/ad34/*/.*'),
				// ],
				external: [
					...external,
					...(JSON.parse(env.VITE_OPEN_CDN) ? buildConfig.external : []),
				],
			},
		},
		css: {
			preprocessorOptions: {
				css: { charset: false },
				// define global scss variable
				scss: {
					additionalData: `@use '@/styles/global/index.scss' as *;`,
				},
			},
		},
		define: {
			__NEXT_VERSION__: JSON.stringify(process.env.npm_package_version),
			__NEXT_NAME__: JSON.stringify(process.env.npm_package_name),
		},
	};
});

export default viteConfig;
